import Logistics from '@/components/TimeLine';
import RightFixed from '@/layouts/RightFixed';
import TopBread from '@/layouts/TopBread';
import { selectByOrderId } from '@/services/evaluate';
import { getOrderList, updState } from '@/services/orders';
import { colorStr, getQueryParams } from '@/utils/utils';
import { Button, Menu, message, Modal, Table } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';
import CreateEvaluate from './components/CreateEvaluate';
import ReturnGoods from './components/ReturnGoods';
import SeeEvaluate from './components/SeeEvaluate';
import { COLUMNS, State_Item } from './constants';
import styles from './index.less';

const StreamPage: React.FC = () => {
  const [color, setColor] = useState<string>(localStorage.getItem('color') || '#1a7721');
  const { tableState, lastRoute }: any = history?.location?.query;
  const qs = getQueryParams();
  const [menuKey, setMenuKey] = useState(tableState);
  const [logisticsModal, setLogisticsModal] = useState<boolean>(false);
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [orderId, setOrderId] = useState<string>('');
  const [state, setState] = useState(0);
  const [evaluate, setEvaluate] = useState<boolean>(false);
  const [info, setInfo] = useState({});
  const [content, setContent] = useState({});
  const [seeEvaluate, setSeeEvaluate] = useState<boolean>(false);
  const [returnModal, setReturnModal] = useState<boolean>(false);

  // 分页的方法
  const handlePageChange = (page: any) => {
    setCurrentPage(page);
  };

  const getList = useCallback(
    async (stateKey: any) => {
      try {
        const res = await getOrderList({
          pageIndex: currentPage,
          menuKey: stateKey,
          userId: qs.id,
        });
        setTotal(res.total);
        setList(res.list);
      } catch (error) {
        console.error(error);
      }
    },
    [currentPage, qs.id],
  );
  const getListCurr = () => {
    getList(menuKey);
  };

  const updStateOrder = (id: string, willState: string, payId: string) => {
    console.log(payId);
    if (willState === '4') {
      Modal.confirm({
        content: '是否确认签收？',
        centered: true,
        okText: '签收',
        cancelText: '取消',
        onOk: async () => {
          await updState({ id: id, state: willState, payId: payId }).then(() => {
            getList(menuKey);
            message.success('签收成功!');
          });
        },
      });
    } else {
      setReturnModal(true);
      setOrderId(id);
    }
  };

  const selectEvaluate = async (id: string) => {
    await selectByOrderId({ orderid: id }).then((res) => {
      setContent({
        ...content,
        star: Number(res.star),
        usercontent: res.usercontent,
        companycontent: res.companycontent,
        ifreply: res.ifreply,
      });
    });
  };

  useEffect(() => {
    getList('0');
  }, [getList]);

  // 切换订单状态展示元素
  const menuChange = (e: any) => {
    setMenuKey(e.key);
    getList(e.key);
  };

  const columns = COLUMNS.map((item: any) => {
    let columnsItem = item;

    if (item.key === 'goodsname') {
      columnsItem.render = (_: any, record: any) => (
        <div
          key={record.id}
          className={styles.goodsname}
          onClick={() => {
            history.push({
              pathname: '/commodity',
              query: { id: record.goodsid, lastRoute: '订单详情' },
            });
          }}
        >
          {record.goodsname}
        </div>
      );
    }
    if (item.key === 'shopAction') {
      columnsItem.render = (_: any, record: any) => {
        return (
          <div className={styles.action} key={record.id}>
            {record.state < 8 && (
              <Button
                className={styles.actionBtn}
                style={{
                  background: colorStr(3),
                  border: color,
                  color: '#fff',
                  marginRight: 10,
                }}
                onClick={() => {
                  setLogisticsModal(true);
                  setOrderId(record.id);
                  setState(record.state);
                }}
              >
                查看物流
              </Button>
            )}
            {record.state === '3' && (
              <>
                <Button
                  className={styles.actionBtn}
                  style={{
                    background: colorStr(3),
                    border: color,
                    marginRight: 10,
                    color: '#fff',
                  }}
                  onClick={() => {
                    updStateOrder(record.id, '4', record.payId);
                  }}
                >
                  签收
                </Button>
                <Button
                  className={styles.actionBtn}
                  style={{
                    background: colorStr(3),
                    border: color,
                    color: '#fff',
                  }}
                  onClick={() => {
                    updStateOrder(record.id, '9', '');
                  }}
                >
                  退货
                </Button>
              </>
            )}
            {record.state === '4' && (
              <Button
                className={styles.actionBtn}
                style={{
                  background: colorStr(3),
                  border: color,
                  color: '#fff',
                }}
                onClick={() => {
                  if (qs.disable === '2' || qs.disable === '3') {
                    message.error('由于您的不当发言，您已被禁止评价！');
                  } else {
                    setEvaluate(true);
                    setOrderId(record.id);
                    setInfo({
                      ...info,
                      orderId: record.id,
                      companyid: record.companyid,
                      userid: record.userid,
                      goodsId: record.goodsid,
                      username: record.username,
                    });
                  }
                }}
              >
                评价
              </Button>
            )}
            {record.state === '5' && (
              <Button
                className={styles.actionBtn}
                style={{
                  background: colorStr(3),
                  border: color,
                  color: '#fff',
                }}
                onClick={() => {
                  setSeeEvaluate(true);
                  selectEvaluate(record.id);
                }}
              >
                查看评价
              </Button>
            )}
          </div>
        );
      };
    }
    if (item.key === 'goodsState') {
      columnsItem.render = (_: any, record: any) => (
        <div key={record.id}>
          {State_Item.map((name: any) => {
            if (name.key === record.state) {
              return name.some;
            } else {
              return '';
            }
          })}
        </div>
      );
    }
    return item;
  });

  return (
    <div className={styles.container}>
      <TopBread lastRoute={lastRoute} now={'我的订单'} setColorParent={setColor} />
      <div className={styles.contentStyle}>
        <Menu
          mode="horizontal"
          className={styles.menuStyle}
          onClick={menuChange}
          defaultSelectedKeys={[menuKey]}
        >
          <Menu.Item key={'0'}>所有订单</Menu.Item>
          <Menu.Item key={'1'}>待发货</Menu.Item>
          <Menu.Item key={'2'}>待收货</Menu.Item>
          <Menu.Item key={'3'}>待评价</Menu.Item>
        </Menu>
        <Table
          className={styles.contentTable}
          columns={columns}
          dataSource={list}
          bordered // 表格的border
          pagination={{
            total,
            current: currentPage, // 当前页数
            pageSize: 10, // 每页条数
            size: 'small', // 分页的样式
            hideOnSinglePage: true, // 只有一页时是否隐藏分页器
            onChange: handlePageChange, // 分页的方法
          }}
        />
      </div>
      <RightFixed color={color} thisRoute={'我的订单'} />
      <Logistics
        state={state}
        color={color}
        orderId={orderId}
        operattime={undefined}
        visible={logisticsModal}
        onCancel={() => {
          setLogisticsModal(false);
        }}
      />
      <CreateEvaluate
        visible={evaluate}
        handleCancel={() => {
          setEvaluate(false);
        }}
        info={info}
        getListCurr={getListCurr}
      />
      <SeeEvaluate
        visible={seeEvaluate}
        handleCancel={() => {
          setSeeEvaluate(false);
        }}
        content={content}
      />
      <ReturnGoods
        visible={returnModal}
        handleCancel={() => {
          setReturnModal(false);
          setOrderId('');
        }}
        orderId={orderId}
        getList={() => {
          getList('0');
        }}
      />
    </div>
  );
};

export default StreamPage;
